<template>
  <div>
    <Header></Header>
    <div class="app-container" style="margin-top:-90px;margin-bottom:-100px">
      <el-card>
        <el-tabs tab-position="left">
          <!--基本设置-->
          <el-tab-pane label="个人设置">
            <h4 class="tab-header">个人设置</h4>
            <div class="tab-view">
              <div class="tab-left">
                <el-form ref="ruleBase" :model="form" :rules="rulesBase" size="small">
                  <el-form-item label="用户名（不可修改）"  >
                    <el-input v-model="form.username" disabled/>
                  </el-form-item>
                  <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" />
                  </el-form-item>
                  <el-form-item label="真实姓名" prop="realname">
                    <el-input v-model="form.realname" />
                  </el-form-item>
                  <el-form-item label="手机号码" prop="telephone">
                    <el-input v-model="form.telephone" />
                  </el-form-item>
                </el-form>
                <el-button type="primary" size="mini" @click="handleUpdate('ruleBase')">更新基本信息</el-button>
              </div>
              <!--头像信息-->
<!--              <div class="tab-right">-->
<!--                <p><label>头像</label></p>-->
<!--                <el-avatar :size="100" fit="fill" :src="form.avatar" />-->
<!--                <div>-->
<!--                  <el-button plain size="mini" icon="el-icon-upload2" @click="handleAvatar">更换头像</el-button>-->
<!--                </div>-->
<!--              </div>-->
            </div>
          </el-tab-pane>
          <!--修改密码-->
          <el-tab-pane label="修改密码">
            <h4 class="tab-header">修改密码</h4>
            <div class="tab-view">
              <div class="tab-left">
                <el-form ref="rulePass" :model="passForm" :rules="rulesPass" size="small">
                  <el-form-item label="新密码" prop="password">
                    <el-input v-model="passForm.password" type="password" />
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="rePass">
                    <el-input v-model="passForm.rePass" type="password" />
                  </el-form-item>
                </el-form>
                <el-button type="primary" size="mini" @click="handleUpdatePass('rulePass')">更新密码</el-button>
              </div>
              <div class="tab-right" />
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-card>
      <!--显示头像-->
<!--      <avatar :form="form" :dialog-visible="dialogVisible" @modelOpen="changeAvatar" />-->
    </div>
    <Footer></Footer>
  </div>

</template>

<script>
  import { mapGetters } from 'vuex'
  // import Avatar from './components/Avatar'
  import Header from "@/components/Header";
  import Footer from "@/components/Footer";
  import Element from "element-ui";
  export default {
    name: 'PersonSetting',
    components: { Header,Footer },
    data(){
      // 检验用户名
      let validateName = (rule, value, callback) => {
        if (value === '' || value === undefined) {
          callback(new Error('请输入登录账户'))
        } else {
          this.findUserByName(value).then(res => {
            if (res.data != null) {
              callback(new Error('该用户名已存在'))
            } else {
              callback()
            }
          }).catch(() => {
            callback(new Error('服务器错误'))
          })
        }
      }
      // 检验密码
      let validateRePass = (rule, value, callback) => {
        if (value === '' || value === undefined) {
          callback(new Error('请输入原密码'))
        } else {
          if (this.passForm.password != value) {
            callback(new Error('两次输入的密码不一致'))
          }
          callback()
        }
      }

      return {
        form: {
          userId:"",
          username:"",
          avater:"",
          email:"",
          realname:"",
          telephone:"",
          last_login:""
        },
        passForm: {
          password:"",
          rePass:"",
          userId:""
        },
        // 规则
        rulesBase: {
          username: [
            { validator: validateName, required: true, trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ],
          email: [
            { required: true, type: 'email', message: '请输入合法邮箱', trigger: 'blur' }
          ],
          realname: [
            { required: true,  message: '请输入真实姓名', trigger: 'blur' }
          ],
          telephone: [
            { required: true, message: '请输入合法手机号', trigger: 'blur' }
          ]
        },
        // 密码的规则
        rulesPass: {
          password: [
            { required: true, message: '请输入原密码', trigger: 'blur' }
          ],
          rePass: [
            { validator: validateRePass, required: true, trigger: 'blur' }
          ]
        },
        list: [],
        dialogVisible: false
      }
    },
    computed: {
      ...mapGetters([
        'name'
      ])
    },
    mounted() {
      this.fetchData()
    },
    methods: {
      handleClose() {
        this.dialogVisible = false
      }, // 赋值
      fetchData() {
        const _this = this
        let username = this.$store.getters.getUserInfo.username
        this.findUserByName(username).then(res => {
          console.log("234324j")
          if (res.status === 200) {
            console.log("643287643287t5rgebbdgfvdfsjdvgvj")
            _this.form = res.data.data
          } else {
            _this.$message.error(res.msg)
          }
        })

      },
      // 更换头像
      // changeAvatar() {
      //   const _this = this
      //   this.disalogVisible = false
      //   this.updateUser({
      //     id: this.form.userId,
      //     avatar: this.form.avatar
      //   }).then(res => {
      //     if (res.status === 200) {
      //       this.$confirm('更新用户头像成功，重新登录后生效，立即重新登录？', '提示', {
      //         confirmButtonText: '确定',
      //         cancelButtonText: '取消',
      //         type: 'success'
      //       }).then(() => {
      //
      //         // 退出
      //         _this.$axios.get("/logout", {
      //           headers: {
      //             "Authorization": localStorage.getItem("token")
      //           }
      //         }).then(res => {
      //           console.log(res)
      //           _this.$store.commit("REMOVE_INFO")
      //           Element.Message.info("注销成功 !");
      //           _this.$router.replace("/login")
      //         })
      //
      //       })
      //     } else {
      //       this.$message.error(res.msg)
      //     }
      //   })
      // },
      // // 显示头像等
      // handleAvatar() {
      //   this.dialogVisible = true
      // },

      // 提交并更新信息
      handleUpdate(formName) {
        const _this = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            _this.updateUser(this.form).then(res => {
              if (res.status === 200) {
                _this.$alert('更新用户信息成功，立即重新登录？', '提示', {
                  confirmButtonText: '确定',
                  type: 'success'
                }).then(() => {
                  // 注销并且跳转到登录页面
                  //首先调用后端logout接口(因该接口需要认证权限,所以需要传入token)
                  //其次调用$store清除用户信息及token
                  _this.$axios.get("/logout", {
                    headers: {
                      "Authorization": localStorage.getItem("token")
                    }
                  }).then(res => {
                    console.log(res)
                    _this.$store.commit("REMOVE_INFO")
                    Element.Message.info("注销成功 !");
                    _this.$router.replace("/login")
                  })
                })
              } else {
                _this.$message.error(res.msg)
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },
      // 修改密码
      handleUpdatePass(formName) {
        const _this = this
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.changePass(this.passForm).then(res => {
              if (res.status === 200) {
                this.$alert('修改账户密码成功，立即重新登录？', '提示', {
                  confirmButtonText: '确定',
                  type: 'success'
                }).then(() => {
                  // 注销并且跳转到登录页面
                  //首先调用后端logout接口(因该接口需要认证权限,所以需要传入token)
                  //其次调用$store清除用户信息及token
                  _this.$axios.get("/logout", {
                    headers: {
                      "Authorization": localStorage.getItem("token")
                    }
                  }).then(res => {
                    console.log(res)
                    _this.$store.commit("REMOVE_INFO")
                    Element.Message.info("注销成功 !");
                    _this.$router.replace("/login")
                  })

                })
              } else {
                this.$message.error(res.msg)
              }
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      },

     //  获取用户信息
      findUserByName(username) {
        const token = this.$store.getters.getToken;
        if(token){
          return this.$axios.get("/user/userinfo/"+username);
        } else {
          // 没有token 说明没有登录
          this.$router.replace("/login")
        }
      },

      // 更新用户信息
      updateUser(form) {
        const token = this.$store.getters.getToken;
        if(token){
          return this.$axios.put("/user/save/",form);
        } else {
          this.$router.replace("/login")
        }
        // return request({
        //   url: '/user/',
        //   method: 'put',
        //   data: data
        // })
      },

      changePass(passForm) {
        const token = this.$store.getters.getToken;
        passForm.userId = this.form.userId
        if(token){
          return this.$axios.put("/user/password/",passForm);
        } else {
          this.$router.replace("/login")
        }

        //   return request({
        //     url: '/user/changePass',
        //     method: 'put',
        //     data: data
        //   })
        // }
      }

    }
  }
</script>
<style lang="css" scoped>
  ::v-deep .el-tabs__header{width:224px;border-right:1px solid #f0f0f0}
  ::v-deep .el-tabs__nav-wrap{border:0}
  ::v-deep .el-tabs--left .el-tabs__item.is-left{padding-left:24px;text-align:left}
  ::v-deep .el-tabs__item:after{transform:scaleY(1);opacity:1;transition:transform .15s cubic-bezier(.645,.045,.355,1),opacity .15s cubic-bezier(.645,.045,.355,1);position:absolute;top:0;right:0;bottom:0;border-right:3px solid #1890ff;transform:scaleY(.0001);opacity:0;transition:transform .15s cubic-bezier(.215,.61,.355,1),opacity .15s cubic-bezier(.215,.61,.355,1);content:""}
  ::v-deep .el-tabs__item.is-active{font-weight:700;background-color:#e6f7ff}
  ::v-deep .el-tabs__item{font-variant:tabular-nums;font-feature-settings:"tnum","tnum";font-weight:500;color:rgba(0,0,0,.65);font-size:14px;text-align:left;list-style:none}
  ::v-deep .el-tabs__content{flex:1 1;padding:8px 40px}
  ::v-deep h4.tab-header{margin-bottom:12px;color:rgba(0,0,0,.85);font-weight:500;font-size:20px;line-height:28px}
  ::v-deep .tab-view{display:flex;padding-top:12px}.tab-left{min-width:280px;max-width:448px}.tab-right{flex:1 1;padding-left:104px}
  ::v-deep .avatar-img{width:100px;height:100px;display:inline-block;margin:10px;overflow:hidden;position:relative;border-radius:5%}
  ::v-deep .avatar-img img{width:100px;height:100px;z-index:1}
  ::v-deep .avatar-img img:hover{cursor:pointer}
  ::v-deep .avatar-img-label{position:absolute;right:-17px;top:-7px;width:46px;height:26px;background:#13ce66;text-align:center;transform:rotate(45deg);box-shadow:0 1px 1px #ccc}
  ::v-deep .avatar-img-label .el-icon-check{font-size:12px;margin-top:12px;transform:rotate(-45deg);color:#fff}
</style>
